package com.clstu.preparedstatement;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

/**
 * 演示PreparedStatement的使用,可以防sql注入...效率高,拼接方便等特点...
 */
public class PreparedStatement_ {
    public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {

        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);

        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名:");
        String name = scanner.nextLine();//注意这里不能用next(),next()读到空格或者'会自动结束,后面读不到了,nextLine读到换行才结束
        System.out.print("请输入密码:");//  当输入万能用户名: 1' or
        String pwd = scanner.nextLine();//      万能密码: or '1'='1 的时候,都能成功登陆 .,这就是sql注入!!!!!(甚至可能破坏你的数据)
        /*
            现在,用prepareStatement接口的时候,就已经安全了,sql注入不生效了,万能密码会被控制住,相对安全,而且预编译(只编译一次)效率也很高
         */
        String sql = "select * from us where name = ? and pwd = ?";//生成sql语句(?表示占位符)
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,name);//给占位符复制,1表示第1个问号...
        preparedStatement.setString(2,pwd);
        /*
           注意:查询用 executeQuery()方法,但是dml(增删改) 用的是 executeUpdate()方法
         */
        ResultSet resultSet = preparedStatement.executeQuery();//这里不能填sql语句了!!!!,除非是一条完整的sql语句
        if(resultSet.next()){//如果有结果,就登陆成功
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }
        //关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
